package com.campuscarbooking.api.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.campuscarbooking.api.model.Driver;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.math.BigDecimal;
import java.util.List;

@Mapper
public interface DriverMapper extends BaseMapper<Driver> {

    /**
     * 查询指定工作状态的司机信息
     */
    @Select("SELECT d.* FROM drivers d WHERE d.work_status = #{workStatus} AND d.status = 'verified'")
    IPage<Driver> findByWorkStatus(Page<?> page, @Param("workStatus") String workStatus);

    /**
     * 更新司机位置信息
     */
    @Update("UPDATE drivers SET current_location_lat = #{lat}, current_location_lng = #{lng}, " +
            "updated_at = NOW() WHERE id = #{driverId}")
    int updateDriverLocation(
            @Param("driverId") Long driverId,
            @Param("lat") BigDecimal lat,
            @Param("lng") BigDecimal lng);

    /**
     * 更新司机工作状态
     */
    @Update("UPDATE drivers SET work_status = #{workStatus}, updated_at = NOW() WHERE id = #{driverId}")
    int updateDriverWorkStatus(
            @Param("driverId") Long driverId,
            @Param("workStatus") String workStatus);

    /**
     * 更新司机评分
     */
    @Update("UPDATE drivers SET rating = #{rating}, updated_at = NOW() WHERE id = #{driverId}")
    int updateDriverRating(
            @Param("driverId") Long driverId,
            @Param("rating") BigDecimal rating);

    /**
     * 查询附近的可用司机
     */
    @Select("SELECT d.*, " +
            "ROUND(6371 * acos(cos(radians(#{lat})) * cos(radians(d.current_location_lat)) * " +
            "cos(radians(d.current_location_lng) - radians(#{lng})) + " +
            "sin(radians(#{lat})) * sin(radians(d.current_location_lat))), 2) AS distance " +
            "FROM drivers d " +
            "WHERE d.work_status = 'available' AND d.status = 'verified' " +
            "HAVING distance < #{radiusKm} " +
            "ORDER BY distance")
    List<Driver> findNearbyAvailableDrivers(
            @Param("lat") BigDecimal lat,
            @Param("lng") BigDecimal lng,
            @Param("radiusKm") Double radiusKm);
} 